package co.baiku.boot.expand;

import weibo4j.Weibo;
import weibo4j.http.ImageItem;
import weibo4j.model.PostParameter;
import weibo4j.model.Status;
import weibo4j.model.WeiboException;
import weibo4j.util.WeiboConfig;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Share extends Weibo {

    public Status uploadStatus(String token, String status, File file)
            throws WeiboException, IOException {
        client.setToken(token);
        if (file != null) {
            ImageItem item = new ImageItem("pic", readFileImage(file));
            return new Status(client.multPartURL(WeiboConfig.getValue("baseURL")
                            + "statuses/share.json",
                    new PostParameter[]{new PostParameter("status", status)},
                    item));
        } else {
            return new Status(client.post(WeiboConfig.getValue("baseURL")
                            + "statuses/share.json",
                    new PostParameter[]{new PostParameter("status", status)}));
        }

    }

    public Status uploadStatus(String token, String status) throws IOException, WeiboException {
        return uploadStatus(token, status, null);
    }


    public static byte[] readFileImage(File file) throws IOException {
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                new FileInputStream(file));) {
            int len = bufferedInputStream.available();
            byte[] bytes = new byte[len];
            int r = bufferedInputStream.read(bytes);
            if (len != r) {
                bytes = null;
                throw new IOException("读取文件不正确");
            }
            return bytes;
        }
    }
}
